package com.example.myapplication.old.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;
import com.example.myapplication.entity.Msg;

import java.util.ArrayList;
import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatHolder> {

    private List<Msg> msgList=new ArrayList<>();
    public ChatAdapter() {
    }

    public void setmsg(Msg msg){
        msgList.add(msg);
        if(msgList.size() % 2 == 0){
            msg.setType(Msg.Other);
        }else{
            msg.setType(Msg.Mine);
        }
        notifyDataSetChanged();
    }
    public void setimg(List<Msg> msgList){
        this.msgList=msgList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ChatHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if(viewType== Msg.Mine){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mine,parent,false);
        }
        else if(viewType == Msg.Other){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_other,parent,false);
        }
        else if(viewType == Msg.Img_Mine){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_img_mine,parent,false);
        }
        else{
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_img_other,parent,false);
        }
        return new ChatHolder(view);
    }

    @Override
    public int getItemViewType(int position) {
        return msgList.get(position).getType();
    }

    @Override
    public void onBindViewHolder(@NonNull ChatHolder holder, int position) {
        Msg msg = msgList.get(position);
        if(msg.getType()==Msg.Mine){
            holder.msg.setText(msg.getMsg());
        }
        else if(msg.getType()==Msg.Other){
            holder.msg.setText(msg.getMsg());
        }
        else if(msg.getType()==Msg.Img_Mine){
            holder.img.setImageResource(msg.getImg());
        }
        else{
            holder.img.setImageResource(msg.getImg());
        }
    }

    @Override
    public int getItemCount() {
        return msgList == null? 0 : msgList.size();
    }

    class ChatHolder extends RecyclerView.ViewHolder {
        TextView msg;
        ImageView img;
        public ChatHolder(@NonNull View itemView) {
            super(itemView);
            msg=itemView.findViewById(R.id.msg);
            img=itemView.findViewById(R.id.chat_img);
        }
    }
}
